<template>
    <div class="device-tab-wrapper">
        <div class="top-bar">
            <a-form layout="inline">
                <!-- 串口模式显示 -->
                <template v-if="currentDeviceUpdateMode === 'serialport'">
                    <a-form-item label="串口">
                        <a-select 
                            v-model="selectedSerialPort" 
                            placeholder="请选择串口" 
                            style="width: 200px;" 
                            :disabled="isSerialPortOpen"
                            @focus="loadSerialPorts"
                        >
                            <a-select-option v-for="serialPort in serialPorts" :key="serialPort" :value="serialPort">
                                {{ serialPort }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="波特率">
                        <a-select 
                            v-model="baudRate" 
                            style="width: 100px;"
                            :disabled="isSerialPortOpen"
                        >
                            <a-select-option v-for="rate in baudRates" :key="rate" :value="rate">
                                {{ rate }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item>
                        <a-button 
                            :type="isSerialPortOpen ? 'danger' : 'primary'" 
                            :icon="isSerialPortOpen ? 'disconnect' : 'api'"
                            @click="toggleSerialPort"
                        >
                            {{ isSerialPortOpen ? '关闭串口' : '打开串口' }}
                        </a-button>
                    </a-form-item>
                </template>
                
                <!-- 网络模式显示 -->
                <template v-else>
                    <a-form-item label="IP 地址">
                        <a-input v-model="ipAddress" placeholder="请输入IP地址" style="width: 200px;" />
                    </a-form-item>
                    <a-form-item label="端口">
                        <a-input v-model="port" style="width: 100px;" />
                    </a-form-item>
                    <a-form-item>
                        <a-button 
                            icon="api" 
                            :loading="isNetworkTesting"
                            :disabled="isNetworkTesting"
                            @click="testNetwork"
                        >
                            {{ isNetworkTesting ? '测试中...' : '网络测试' }}
                        </a-button>
                    </a-form-item>
                </template>
                
                <!-- 通用按钮 -->
                <a-form-item>
                    <a-button icon="download" class="action-btn" @click="downloadConfig">下载配置</a-button>
                </a-form-item>
                <a-form-item>
                    <a-button icon="file-add" class="action-btn" @click="generateFile">生成文件</a-button>
                </a-form-item>
                <a-form-item>
                    <a-button type="dashed" class="action-btn" @click="testStatusUpdate">测试状态更新</a-button>
                </a-form-item>
            </a-form>
        </div>
        <div class="device-tab-container">
            <!-- 左侧按钮区域 -->
            <div class="left-sidebar">
                <div class="sidebar-buttons">
                    <button class="sidebar-btn active" @click="switchTab('deviceSearch', $event)">
                        <div class="btn-icon">🔍</div>
                        <div class="btn-text">设备查找</div>
                    </button>
                    <button class="sidebar-btn" @click="switchTab('firmwareUpdate', $event)">
                        <div class="btn-icon">📱</div>
                        <div class="btn-text">更新固件</div>
                    </button>
                    <button class="sidebar-btn" @click="switchTab('gatewayRestart', $event)">
                        <div class="btn-icon">🔄</div>
                        <div class="btn-text">网关重启</div>
                    </button>
                    <button class="sidebar-btn" @click="switchTab('updateToServer', $event)">
                        <div class="btn-icon">☁️</div>
                        <div class="btn-text">更新到服务器</div>
                    </button>
                    <button class="sidebar-btn" @click="switchTab('updateToDevice', $event)">
                        <div class="btn-icon">📡</div>
                        <div class="btn-text">更新到设备</div>
                    </button>
                </div>
            </div>
            
            <!-- 右侧内容区域 -->
            <div class="content-area">
                <DeviceSearch v-if="currentTab === 'deviceSearch'" @connection-success="onConnectionSuccess" />
                <FirmwareUpdate v-if="currentTab === 'firmwareUpdate'" 
                                :ip-address="ipAddress"
                                :port="port"
                />
                <GatewayRestart v-if="currentTab === 'gatewayRestart'" 
                                :ip-address="ipAddress"
                                :port="port"
                />
                <UpdateToServer v-if="currentTab === 'updateToServer'" 
                                :ip-address="ipAddress"
                                :port="port"
                />
                <UpdateToDevice v-if="currentTab === 'updateToDevice'" 
                                :ip-address="ipAddress"
                                :port="port"
                />
            </div>
        </div>
        
        <!-- 下载进度组件 -->
        <DownloadProgress 
            :visible.sync="showDownloadModal" 
            :device-update-mode="currentDeviceUpdateMode"
            :is-serial-port-open="isSerialPortOpen"
            :network-params="{ ipAddress, port }"
            @download-started="onDownloadStarted"
            @download-completed="onDownloadCompleted"
            @download-stopped="onDownloadStopped"
        />
    </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import DeviceSearch from '@/components/DeviceTab/DeviceSearch.vue'
import FirmwareUpdate from '@/components/DeviceTab/FirmwareUpdate.vue'
import GatewayRestart from '@/components/DeviceTab/GatewayRestart.vue'
import UpdateToServer from '@/components/DeviceTab/UpdateToServer.vue'
import UpdateToDevice from '@/components/DeviceTab/UpdateToDevice.vue'
import DownloadProgress from '@/components/DeviceTab/DownloadProgress.vue'
import DeviceTabManager from '@/api/TabManager/DeviceTabManager'
import { GATEWAY_CONFIGS } from '@/config/gateway-config'

export default {
    name: 'DeviceTab',
    components: {
        DeviceSearch,
        FirmwareUpdate,
        GatewayRestart,
        UpdateToServer,
        UpdateToDevice,
        DownloadProgress
    },
    data() {
        return {
            currentTab: 'deviceSearch',
            ipAddress: '',
            port: '8888',
            selectedSerialPort: '',
            baudRate: '9600',
            serialPorts: [],
            baudRates: ['9600', '19200', '38400', '57600', '115200'],
            isSerialPortOpen: false, // 新增：串口是否打开
            deviceTabManager: new DeviceTabManager(), // 新增：管理器实例
            isUpdatingDeviceStatus: false, // 新增：防止状态重置的标志
            isNetworkTesting: false, // 新增：网络测试加载状态
            isDeviceSwitching: false, // 新增：设备切换状态标志
            showDownloadModal: false // 新增：下载进度Modal可见性
        }
    },
    computed: {
        ...mapGetters('groupTree', ['selectedDeviceInfo', 'deviceConnection']),
        
        currentDeviceUpdateMode() {
            if (!this.selectedDeviceInfo) {
                return 'ethernet' // 默认为网络模式
            }
            
            // 根据设备类型获取updateMode
            const deviceType = this.selectedDeviceInfo.gatewayType || this.selectedDeviceInfo.deviceType
            const config = GATEWAY_CONFIGS[deviceType]
            
            if (config && config.hardwareInfo && config.hardwareInfo.updateMode) {
                return config.hardwareInfo.updateMode
            }
            
            // 如果直接有updateMode属性，使用它
            if (this.selectedDeviceInfo.updateMode) {
                return this.selectedDeviceInfo.updateMode
            }
            
            return 'ethernet' // 默认为网络模式
        }
    },
    watch: {
        // 监听IP地址变化，同步到Vuex
        ipAddress(newVal) {
            this.updateDeviceConnection({
                ipAddress: newVal
            })
        },
        
        // 监听端口变化，同步到Vuex
        port(newVal) {
            this.updateDeviceConnection({
                port: newVal
            })
        },
        
        // 监听串口变化，同步到Vuex
        selectedSerialPort(newVal) {
            this.updateDeviceConnection({
                selectedSerialPort: newVal
            })
        },
        
        // 监听波特率变化，同步到Vuex
        baudRate(newVal) {
            this.updateDeviceConnection({
                baudRate: newVal
            })
        },
        
        selectedDeviceInfo: {
            async handler(newVal, oldVal) {
                // 防止设备状态更新时的重复处理
                if (this.isUpdatingDeviceStatus || this.isDeviceSwitching) {
                    return
                }
                
                if (newVal) {
                    // 检查是否是真正的设备切换
                    const isRealDeviceSwitch = oldVal && (oldVal.id !== newVal.id || oldVal.key !== newVal.key)
                    
                    if (isRealDeviceSwitch && this.isSerialPortOpen) {
                        // 设备切换且串口已打开，需要确认是否关闭串口
                        console.log('🔄 [DeviceTab] 检测到设备切换，串口已打开，需要确认关闭')
                        
                        this.isDeviceSwitching = true
                        
                        try {
                            await this.$confirm({
                                title: '串口关闭确认',
                                content: '当前设备的串口正在使用中，切换到新设备前需要关闭串口。是否继续？',
                                okText: '确定关闭',
                                cancelText: '取消切换',
                                type: 'warning'
                            })
                            
                            // 用户确认关闭，执行关闭串口操作
                            console.log('🔄 [DeviceTab] 用户确认关闭串口，开始关闭...')
                            
                            try {
                                // 1. 先关闭串口
                                const response = await this.deviceTabManager.closeSerialPort()
                                if (response.code === 0) {
                                    this.isSerialPortOpen = false
                                    this.$message.success('串口已关闭')
                                    console.log('✅ [DeviceTab] 串口关闭成功')
                                    
                                    // 2. 将之前设备设置为离线状态
                                    if (oldVal) {
                                        console.log('🔄 [DeviceTab] 将之前设备设置为离线:', oldVal.name)
                                        await this.updatePreviousDeviceStatus(oldVal, false)
                                    }
                                } else {
                                    this.$message.error('关闭串口失败: ' + response.msg)
                                    console.error('❌ [DeviceTab] 串口关闭失败:', response.msg)
                                    // 关闭失败，恢复设备选择
                                    this.revertToDevice(oldVal)
                                    return
                                }
                            } catch (error) {
                                console.error('❌ [DeviceTab] 串口关闭异常:', error)
                                this.$message.error('关闭串口异常: ' + error.message)
                                // 关闭失败，恢复设备选择
                                this.revertToDevice(oldVal)
                                return
                            }
                            
                        } catch (cancelError) {
                            // 用户取消了操作，恢复到原来的设备
                            console.log('🚫 [DeviceTab] 用户取消设备切换，恢复原设备')
                            this.revertToDevice(oldVal)
                            return
                        } finally {
                            this.isDeviceSwitching = false
                        }
                    }
                    
                    console.log('Selected device changed:', newVal)
                    console.log('Update mode:', this.currentDeviceUpdateMode)
                    
                    // 如果是串口模式，加载串口列表
                    if (this.currentDeviceUpdateMode === 'serialport') {
                        this.loadSerialPorts()
                    }
                    
                    // 只有在非状态更新时才重置串口状态（如果没有在上面处理串口关闭）
                    if (!this.isUpdatingDeviceStatus && !isRealDeviceSwitch) {
                        console.log('🔄 [DeviceTab] 设备切换，重置串口状态')
                        this.isSerialPortOpen = false
                    } else {
                        console.log('🔄 [DeviceTab] 设备状态更新中，保持串口状态')
                    }
                } else {
                    console.log('🧹 [DeviceTab] 设备信息被清空')
                    this.isSerialPortOpen = false
                }
            },
            immediate: true
        }
    },
    methods: {
        ...mapActions('groupTree', ['setSelectedDevice', 'updateDeviceConnection']),
        
        // 恢复到指定设备
        revertToDevice(device) {
            if (!device) {
                console.warn('🚨 [DeviceTab] 无效的设备信息，无法恢复')
                return
            }
            
            console.log('🔄 [DeviceTab] 恢复设备选择:', device.name)
            this.$emit('revertDeviceSelection', device)
        },
        
        // 更新之前设备的状态
        async updatePreviousDeviceStatus(device, isOnline) {
            if (!device || !device.id) {
                console.warn('🚨 [DeviceTab] 无效的设备信息，跳过状态更新')
                return
            }
            
            try {
                console.log('🔄 [DeviceTab] 更新之前设备状态:', {
                    deviceId: device.id,
                    deviceKey: device.key,
                    deviceName: device.name,
                    isOnline: isOnline
                })
                
                // 直接发送事件通知GroupTree更新设备状态，不更新Vuex（因为当前选中设备已经变了）
                const statusInfo = {
                    deviceId: device.id,
                    deviceKey: device.key,
                    online: isOnline
                }
                
                console.log('📤 [DeviceTab] 发送之前设备状态更新事件:', statusInfo)
                this.$emit('updateDeviceStatus', statusInfo)
                
                console.log('✅ [DeviceTab] 之前设备状态更新成功')
            } catch (error) {
                console.error('❌ [DeviceTab] 更新之前设备状态失败:', error)
            }
        },
        
        // 更新设备在线状态
        async updateDeviceOnlineStatus(isOnline) {
            if (!this.selectedDeviceInfo || !this.selectedDeviceInfo.id) {
                console.warn('🚨 [DeviceTab] No selected device to update status:', this.selectedDeviceInfo)
                return
            }
            
            try {
                console.log('🔄 [DeviceTab] 更新设备在线状态:', {
                    deviceId: this.selectedDeviceInfo.id,
                    deviceKey: this.selectedDeviceInfo.key,
                    deviceName: this.selectedDeviceInfo.name,
                    isOnline: isOnline,
                    serialPortStatus: this.isSerialPortOpen
                })
                
                // 设置标志，防止 watcher 重置串口状态
                this.isUpdatingDeviceStatus = true
                
                // 异步更新 Vuex 中的设备状态
                this.$nextTick(() => {
                    const updatedDevice = {
                        ...this.selectedDeviceInfo,
                        online: isOnline
                    }
                    this.setSelectedDevice(updatedDevice)
                })
                
                // 异步通知父组件（GroupTree）更新设备状态
                this.$nextTick(() => {
                    const statusInfo = {
                        deviceId: this.selectedDeviceInfo.id,
                        deviceKey: this.selectedDeviceInfo.key,
                        online: isOnline
                    }
                    console.log('📤 [DeviceTab] 发送设备状态更新事件:', statusInfo)
                    this.$emit('updateDeviceStatus', statusInfo)
                    
                    // 在所有操作完成后清除标志
                    this.$nextTick(() => {
                        this.isUpdatingDeviceStatus = false
                        console.log(' [DeviceTab] 设备状态更新完成，标志已清除')
                    })
                })
                
                console.log('✅ [DeviceTab] 设备状态更新成功')
            } catch (error) {
                console.error('❌ [DeviceTab] 更新设备状态失败:', error)
                // 确保在错误时也清除标志
                this.isUpdatingDeviceStatus = false
            }
        },
        async loadSerialPorts() {
            try {
                const response = await this.deviceTabManager.getSerialPortList()
                if (response.code === 0) {
                    this.serialPorts = JSON.parse(response.data)
                    console.log('Serial ports loaded:', this.serialPorts)
                    // 默认为第一个串口
                    if (this.serialPorts.length > 0) {
                        this.selectedSerialPort = this.serialPorts[0]
                    }
                } else {
                    this.$message.error('获取串口列表失败' + response.msg)
                }
            } catch (error) {
                console.error('Failed to load serial ports:', error)
                this.$message.error('获取串口列表失败' + error)
            }
        },
        
        async testNetwork() {
            if (this.isNetworkTesting) {
                console.log('🔄 [DeviceTab] 网络测试进行中，跳过重复请求')
                return
            }
            
            try {
                this.isNetworkTesting = true
                this.$message.loading('正在测试网络连接...', 0) // 0表示不自动关闭
                
                const params = {
                    ip: this.ipAddress,
                    port: parseInt(this.port)
                }
                
                console.log('🔄 [DeviceTab] 开始网络连接测试:', params)
                const response = await this.deviceTabManager.testNetworkConnection(JSON.stringify(params))
                
                // 关闭loading消息
                this.$message.destroy()
                
                if (response.code === 0) {
                    this.$message.success('网络连接测试成功')
                    console.log('✅ [DeviceTab] 网络连接测试成功')
                    
                    // 更新设备为在线状态
                    await this.updateDeviceOnlineStatus(true)
                } else {
                    this.$message.error('网络连接测试失败: ' + response.msg)
                    console.error('❌ [DeviceTab] 网络连接测试失败:', response.msg)
                }
            } catch (error) {
                // 确保关闭loading消息
                this.$message.destroy()
                console.error('❌ [DeviceTab] 网络测试异常:', error)
                this.$message.error('网络连接测试异常: ' + error.message)
            } finally {
                this.isNetworkTesting = false
            }
        },

        async toggleSerialPort() {
            try {
                if (!this.isSerialPortOpen) {
                    // 打开串口
                    const params = {
                        port: this.selectedSerialPort,
                        baudRate: parseInt(this.baudRate)
                    }
                    const response = await this.deviceTabManager.openSerialPort(JSON.stringify(params))
                    console.log('📥 [DeviceTab] 收到打开串口响应:', response)
                    
                    if (response.code === 0) {
                        this.isSerialPortOpen = true
                        this.$message.success('串口已打开')
                        
                        // 直接调用，方法内部已经优化为异步
                        await this.updateDeviceOnlineStatus(true) 
                        console.log('✅ [DeviceTab] 设备在线状态更新完成')
                    } else {
                        this.$message.error('打开串口失败' + response.msg)
                    }
                } else {
                    // 关闭串口
                    const response = await this.deviceTabManager.closeSerialPort()
                    
                    if (response.code === 0) {
                        this.isSerialPortOpen = false
                        this.$message.success('串口已关闭')
                        // 直接调用，方法内部已经优化为异步
                        await this.updateDeviceOnlineStatus(false)
                        console.log('✅ [DeviceTab] 设备离线状态更新完成')
                    } else {
                        this.$message.error('关闭串口失败' + response.msg)
                    }
                }
                console.log('🔄 [DeviceTab] toggleSerialPort 执行完成')
            } catch (error) {
                console.error('❌ [DeviceTab] Serial port operation failed:', error)
                this.$message.error(this.isSerialPortOpen ? '关闭串口失败' + error : '打开串口失败' + error)
            }
        },

        async downloadConfig() {
            try {
                // 检查串口状态（如果是串口模式）
                if (this.currentDeviceUpdateMode === 'serialport' && !this.isSerialPortOpen) {
                    this.$message.error('请先打开串口')
                    return
                }
                
                // 显示下载进度组件
                this.showDownloadModal = true
                
                // 实际的下载逻辑将由DownloadProgress组件处理
                console.log('🚀 [DeviceTab] 开始下载配置流程')
                
            } catch (error) {
                console.error('❌ [DeviceTab] 启动下载失败:', error)
                this.$message.error('启动下载失败: ' + error.message)
                this.showDownloadModal = false
            }
        },
        
        async generateFile() {
            try {
                let response
                if (this.currentDeviceUpdateMode === 'serialport') {
                    // 串口模式下需要检查串口是否已打开
                    // if (!this.isSerialPortOpen) {
                    //     this.$message.error('请先打开串口')
                    //     return
                    // }
                    // 串口模式生成文件
                    response = await this.deviceTabManager.generateFileViaSerial()
                } else {
                    // 网络模式生成文件
                    const params = {
                        ip: this.ipAddress,
                        port: parseInt(this.port)
                    }
                    response = await this.deviceTabManager.generateFileViaNetwork(params)
                }
                
                if (response.code === 0) {
                    this.$message.success('生成文件成功')
                } else {
                    this.$message.error('生成文件失败')
                }
            } catch (error) {
                console.error('Generate file failed:', error)
                this.$message.error('生成文件失败' + error)
            }
        },

        async testStatusUpdate() {
            console.log('🧪 [DeviceTab] 开始测试设备状态更新')
            console.log('🔍 [DeviceTab] 当前选中设备:', this.selectedDeviceInfo)
            
            if (!this.selectedDeviceInfo) {
                this.$message.error('请先选择一个设备')
                return
            }
            
            try {
                // 测试设置为在线
                console.log('🔄 [DeviceTab] 测试设置设备为在线')
                await this.updateDeviceOnlineStatus(true)
                
                // 2秒后测试设置为离线
                setTimeout(async() => {
                    console.log('🔄 [DeviceTab] 测试设置设备为离线')
                    await this.updateDeviceOnlineStatus(false)
                }, 2000)
                
                this.$message.success('设备状态更新测试已开始，请查看控制台日志')
            } catch (error) {
                console.error('❌ [DeviceTab] 状态更新测试失败:', error)
                this.$message.error('设备状态更新测试失败')
            }
        },

        switchTab(tab, event) {
            this.currentTab = tab
            // 更新按钮的active状态
            document.querySelectorAll('.sidebar-btn').forEach(btn => {
                btn.classList.remove('active')
            })
            event.currentTarget.classList.add('active')
        },

        // 下载进度组件事件处理
        onDownloadStarted() {
            console.log('📥 [DeviceTab] 下载已开始')
        },

        onDownloadCompleted({ success, message }) {
            console.log('📥 [DeviceTab] 下载完成:', { success, message })
            // 下载完成，需要延时关闭(延时5秒)
            setTimeout(() => {
                this.showDownloadModal = false
            }, 5000)
            
            if (success) {
                this.$message.success(message || '下载配置成功')
            } else {
                this.$message.error(message || '下载配置失败')
            }
        },

        onDownloadStopped() {
            console.log('📥 [DeviceTab] 下载已停止')
            this.showDownloadModal = false
            this.$message.info('下载已停止')
        },

        // 处理设备连接成功事件
        onConnectionSuccess(connectionInfo) {
            console.log('🔗 [DeviceTab] 收到设备连接成功事件:', connectionInfo)
            
            // 更新IP地址和端口
            this.ipAddress = connectionInfo.ip
            this.port = connectionInfo.port
            
            // 显示连接信息
            const connectionType = {
                'direct': '直接连接',
                'hub': 'Hub连接', 
                'auto': '自动连接',
                'device': '设备连接'
            }[connectionInfo.type] || '未知连接'
            
            console.log(`✅ [DeviceTab] ${connectionType}成功，已更新IP: ${this.ipAddress}, 端口: ${this.port}`)
            this.$message.success(`${connectionType}成功，IP和端口已更新`)
        }
    }
}
</script>

<style scoped>
.device-tab-wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: #f5f5f5;
}
.top-bar {
    display: flex;
    align-items: center;
    padding: 12px 24px;
    background-color: #fff;
    border-bottom: 1px solid #e8e8e8;
    flex-shrink: 0;
}
.top-bar .ant-form-item {
    margin-bottom: 0;
}
.device-tab-container {
    flex: 1;
    display: flex;
    min-height: 0;
}
.left-sidebar {
    width: 200px;
    background-color: #fff;
    border-right: 1px solid #e0e0e0;
    padding: 20px 0;
    box-shadow: 2px 0 4px rgba(0, 0, 0, 0.05);
}
.sidebar-buttons {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 0 15px;
}
.sidebar-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px 10px;
    border: none;
    background-color: transparent;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    width: 100%;
    text-align: center;
    color: #333;
}
.sidebar-btn:hover {
    background-color: #f0f8ff;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.sidebar-btn.active {
    background-color: #1890ff;
    color: white;
    box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}
.btn-icon {
    font-size: 24px;
    margin-bottom: 8px;
}
.btn-text {
    font-size: 14px;
    font-weight: 500;
    line-height: 1.2;
}

/* 右侧内容区域 */
.content-area {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
}

/* 按钮容器样式 */
.action-btn {
    margin-right: 12px; /* 添加右边距创建间隔 */
}
.action-btn:last-child {
    margin-right: 0; /* 最后一个按钮不需要右边距 */
}
</style> 